<template>
  <div class="startup-plan">
    <div class="page-header">
      <h2>启动方案校验</h2>
      <p>上传启动方案文档，进行智能校验和错误检测</p>
    </div>
    
    <!-- 步骤1：上传 -->
    <el-card class="step-card" v-if="currentStep === 1">
      <template #header>
        <h3>步骤1：上传启动方案</h3>
      </template>
      
      <div class="upload-area">
        <el-upload
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          accept=".docx"
          class="upload-demo"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将启动方案文档拖拽到此处或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 .docx/.doc 格式文档，文件大小不超过50MB
            </div>
          </template>
        </el-upload>
      </div>
      
      <div class="upload-actions">
        <el-button type="primary" @click="uploadPlan" :disabled="fileList.length === 0">
          开始校验
        </el-button>
        <el-button @click="resetUpload">重置</el-button>
      </div>
    </el-card>

    <!-- 步骤2：校验结果 -->
    <el-card class="step-card" v-if="currentStep === 2">
      <template #header>
        <div class="card-header">
          <h3>步骤2：校验结果</h3>
        </div>
      </template>
      
      <div class="result-summary" v-if="validationResult">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="总步骤数">{{ validationResult.totalSteps || 0 }}</el-descriptions-item>
          <el-descriptions-item label="通过步骤">{{ validationResult.passedSteps || 0 }}</el-descriptions-item>
          <el-descriptions-item label="错误步骤">{{ validationResult.failedSteps || 0 }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <div class="validation-actions">
        <el-button @click="backToUpload">重新上传</el-button>
        <el-button type="success" @click="downloadResult" v-if="validationResult">
          下载校验报告
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { startupPlanApi } from '@/services/api'

// 响应式数据
const currentStep = ref(1)
const fileList = ref([])
const validationResult = ref(null)

// 方法
const handleFileChange = (file: any, uploadFileList: any[]) => {
  fileList.value = uploadFileList
}

const uploadPlan = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择文件')
    return
  }
  
  try {
    ElMessage.info('开始校验启动方案...')
    const response = await startupPlanApi.upload(fileList.value[0].raw, '启动方案校验')
    validationResult.value = response
    currentStep.value = 2
    ElMessage.success('校验完成')
  } catch (error) {
    ElMessage.error('校验失败: ' + (error.message || '未知错误'))
  }
}

const resetUpload = () => {
  currentStep.value = 1
  fileList.value = []
  validationResult.value = null
}

const backToUpload = () => {
  currentStep.value = 1
}

const downloadResult = async () => {
  if (!validationResult.value || !validationResult.value.documentId) {
    ElMessage.error('无法获取文档ID')
    return
  }
  
  try {
    ElMessage.info('正在生成下载文件...')
    
    const response = await fetch(`/api/startup-plan/download/${validationResult.value.documentId}`, {
      method: 'GET'
    })
    
    if (!response.ok) {
      throw new Error('下载请求失败')
    }
    
    // 获取文件名
    const contentDisposition = response.headers.get('Content-Disposition')
    let filename = `启动方案校验结果_${validationResult.value.documentId}.docx`
    if (contentDisposition) {
      const matches = contentDisposition.match(/filename="?([^"]+)"?/)
      if (matches && matches[1]) {
        filename = matches[1]
      }
    }
    
    // 创建下载链接
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('下载完成')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败: ' + error.message)
  }
}
</script>

<style scoped>
.startup-plan {
  padding: 40px 0;
}

.page-header {
  text-align: center;
  margin-bottom: 60px;
}

.page-header h2 {
  font-size: 28px;
  color: #2c3e50;
  margin-bottom: 15px;
}

.page-header p {
  font-size: 16px;
  color: #606266;
}

.step-card {
  margin-bottom: 40px;
  min-height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 20px;
  color: #2c3e50;
}

.upload-area {
  margin: 40px 0;
}

.upload-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
}

.result-summary {
  margin: 20px 0;
}

.validation-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}
</style>